package com.fone.player.activity.search;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.yunzhisheng.basic.USCRecognizerDialog;
import cn.yunzhisheng.basic.USCRecognizerDialogListener;
import cn.yunzhisheng.common.USCError;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.activity.search.adapter.SearchGridAdapter;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.HotwordRst;
import com.fone.player.client.HotwordRst.Sk;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.view.HistorySearchPopWindow;
import com.fone.player.view.HistorySearchPopWindow.IDeleteListener;
import com.fone.player.view.LegalNoticeDialog;

public class SearchActivity extends BaseActivity implements OnClickListener {
	private String TAG = "SearchActivity";
	private Button btn_search_back;
	private EditText et_search_content;
	private ImageView iv_search_voice;
	private ImageView iv_search_clear;
	private GridView gv_search_recommond;
	private List<Sk> mHotWords;
	private List<String> mHistoryWords;
	private TextView tv_search;
	private String SP = "search", FILE_NAME = "historyword";
	private SharedPreferences sp;
	private HistorySearchPopWindow popWindow;
	private SearchGridAdapter mSearchAdapter;
	private int SUCCESS = 0;
	public static final int SEARCH_HOT_WORD = 2, SEARCH_NORMAL = 3;// 2:热词列表搜索
																	// 3：手工搜索
	public static final String KeyWord = "KeyWord", SearchType = "SearchType";
	private Button btn_legal_declaration;
	private View loading_view;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_view);
		initView();
		initData();
	}

	private void initData() {
		if (FoneUtil.isNetOkWithToast(mContext)) {
			HotWordCallBack callBack = new HotWordCallBack();
			// 获取推荐词
			mHotWords.clear();
			loading_view.setVisibility(View.VISIBLE);
			Request.getInstance().hotword(callBack);
		}
		// 获取历史搜索记录
		mHistoryWords = new ArrayList<String>();
		popWindow = new HistorySearchPopWindow(mContext, mHistoryWords,
				et_search_content);

		popWindow.setDeleteListener(new IDeleteListener() {
			@Override
			public void deleteAll() {
				mHistoryWords.clear();
				Editor editor = sp.edit();
				editor.putString(FILE_NAME, "");
				editor.commit();
			}

			@Override
			public void delete(int index) {
				mHistoryWords.remove(index);
				saveHistorySearchWords("");
			}

			@Override
			public void selectItem(int position) {
				String HistoryWord = mHistoryWords.get(position);
				et_search_content.setText(HistoryWord);
				et_search_content.setSelection(et_search_content.getText()
						.toString().length());
				doSearch(HistoryWord, SEARCH_NORMAL);
//				saveHistorySearchWords(HistoryWord);
			}
		});
	}

	private void initView() {
		btn_search_back = (Button) findViewById(R.id.btn_search_back);
		iv_search_voice = (ImageView) findViewById(R.id.iv_search_voice);
		iv_search_clear = (ImageView) findViewById(R.id.iv_search_clear);
		tv_search = (TextView) findViewById(R.id.tv_search);
		et_search_content = (EditText) findViewById(R.id.et_search_content);
		btn_legal_declaration = (Button) findViewById(R.id.btn_legal_declaration);
		btn_legal_declaration.setOnClickListener(this);
		et_search_content.setOnClickListener(this);
		loading_view = findViewById(R.id.loading);
		sp = mContext.getSharedPreferences(SP, MODE_PRIVATE);
		et_search_content.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					showHistorySearchPopWindow();
				}
			}
		});
		gv_search_recommond = (GridView) findViewById(R.id.gv_search_recommond);
		btn_search_back.setOnClickListener(this);
		iv_search_voice.setOnClickListener(this);
		iv_search_clear.setOnClickListener(this);
		tv_search.setOnClickListener(this);
		et_search_content.addTextChangedListener(new MyTextWatcher());
		mHotWords = new ArrayList<HotwordRst.Sk>();
		mSearchAdapter = new SearchGridAdapter(mContext, mHotWords);
		gv_search_recommond.setAdapter(mSearchAdapter);
		
		gv_search_recommond.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (FoneUtil.isNetOkWithToast(mContext)) {
					String keyWord = mHotWords.get(position).name;
//					saveHistorySearchWords(keyWord);
					doSearch(keyWord, SEARCH_HOT_WORD);
				}
			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.et_search_content:
			showHistorySearchPopWindow();
			break;
		case R.id.iv_search_voice:
			if (FoneUtil.isNetOkWithToast(mContext)) {
				doVoiceSearch();
			}
			break;

		case R.id.btn_search_back:
			finish();
			break;
		case R.id.iv_search_clear:
			et_search_content.setText("");
			break;
		case R.id.tv_search:
			if (FoneUtil.isNetOkWithToast(mContext)) {
				String key_word = et_search_content.getText().toString().trim();
				doSearch(key_word, SEARCH_NORMAL);
//				saveHistorySearchWords(key_word);
			}
			break;
		case R.id.btn_legal_declaration:
			String Content = FoneUtil.getDeclaration(mContext,
					FoneConstant.SEARCH_LEGAL_NOTICE);
			new LegalNoticeDialog(this, Content);
			break;
		default:
			break;
		}
	}

	// 保存历史搜索记录
	private void saveHistorySearchWords(String key_word) {
		if (!TextUtils.isEmpty(key_word)) {
			if (mHistoryWords.contains(key_word)) {
				mHistoryWords.remove(key_word);
			}
			mHistoryWords.add(0, key_word);
		}
		while (mHistoryWords.size() > 10) {
			mHistoryWords.remove(10);
		}
		String str = "";
		for (int i = mHistoryWords.size() - 1; i >= 0; i--) {
			String historyword = mHistoryWords.get(i);
			if (TextUtils.isEmpty(historyword)) {
				continue;
			}
			L.i(TAG, "save history word:" + mHistoryWords.get(i));
			str = str + "," + mHistoryWords.get(i);
		}
		str = str.replaceFirst(",", "");
		L.i(TAG, "all history words :" + str);
		Editor editor = sp.edit();
		editor.putString(FILE_NAME, str);
		editor.commit();
	}

	/**
	 * 
	 * 搜索
	 * 
	 * @param key_word
	 *            搜索词
	 * @param SearchType
	 *            搜索类型 1、推荐热词搜索 2、手工搜索
	 * @return void
	 * @throws
	 */
	private void doSearch(String key_word, int Search_Type) {
		if (TextUtils.isEmpty(key_word)) {
			String no_search_word = mContext.getResources().getString(
					R.string.no_search_word);
			Toast.makeText(mContext, no_search_word, Toast.LENGTH_SHORT).show();
			return;
		}
		if (FoneUtil.isNetOkWithToast(mContext)) {
			L.i(TAG, "key_word:" + key_word + "   Search_Type:" + Search_Type);
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), SearchResultActivity.class);
			intent.putExtra(KeyWord, key_word);
			intent.putExtra(SearchType, Search_Type);
			et_search_content.setText("");
			closeKeyBoard(et_search_content);
			startActivity(intent);
		}
	}

	// 开启语音搜索
	@SuppressLint("HandlerLeak")
	private void doVoiceSearch() {
		et_search_content.setText("");
		// 用的是原100TV的key
		String key = "wn4lo73d7shfmj5s2eco3punzojc2rrq3yv6ttaq";
		USCRecognizerDialog recognizer = new USCRecognizerDialog(this, key);
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (FoneUtil.isNetOkWithToast(mContext)) {
					String key_word = (String) msg.obj;
					key_word = key_word.trim();
					if (key_word != null && key_word.length() > 1) {
						if(key_word.contains("。")){
							key_word = key_word.substring(0,key_word.indexOf("。"));
						}
						et_search_content.setText(key_word);
						et_search_content
								.setSelection(key_word.length());
//						saveHistorySearchWords(key_word);
					}
				}
			}
		};
		recognizer.setListener(new USCRecognizerDialogListener() {
			@Override
			public void onEnd(USCError arg0) {

			}

			StringBuffer sb = new StringBuffer();

			@Override
			public void onResult(String arg0, boolean arg1) {
				sb.append(arg0);
				if (arg1) {
					Message msg = new Message();
					msg.obj = sb.toString();
					handler.sendMessage(msg);
				}
			}
		});
		recognizer.show();
	}

	private class MyTextWatcher implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

		@Override
		public void afterTextChanged(Editable s) {

			if (s.length() > 0) {
				iv_search_voice.setVisibility(View.GONE);
				tv_search.setVisibility(View.VISIBLE);
				iv_search_clear.setVisibility(View.VISIBLE);
			} else {
				iv_search_voice.setVisibility(View.VISIBLE);
				tv_search.setVisibility(View.GONE);
				iv_search_clear.setVisibility(View.GONE);
			}

		}
	}

	/**
	 * 关闭软键盘
	 * 
	 * @param v
	 */
	private void closeKeyBoard(View v) {
		InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		manager.hideSoftInputFromWindow(v.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	private void showHistorySearchPopWindow() {
		if (popWindow.searchPopWindowisShowing()) {
			return;
		}
		String words = sp.getString(FILE_NAME, null);
		L.i(TAG, "历史记录 words:" + words);
		if (TextUtils.isEmpty(words)) {
			return;
		}
		String[] historyWords = words.split(";;");
		mHistoryWords.clear();
		if (historyWords != null) {
			for (int i = historyWords.length; i > 0; i--) {
				mHistoryWords.add(historyWords[i - 1]);
			}
			popWindow.showPop();
		}
	}

	@Override
	protected void onPause() {
		if (et_search_content != null) {
			et_search_content.clearFocus();
			closeKeyBoard(et_search_content);
		}
		super.onPause();
	}

	// 访问网络 返回回调接口
	private class HotWordCallBack implements Callback<HotwordRst> {

		@Override
		public void onSuccess(HotwordRst t) {
			L.i(TAG, "SearchCallBack:  success");
			loading_view.setVisibility(View.GONE);
			if (t.result == SUCCESS) {
				if (t != null && t.sks != null && t.sks.skList != null) {
					List<Sk> skList = t.sks.skList;
					if (skList == null) {
						L.i(TAG, "SearchCallBack: skList is null!");
						return;
					}
					L.i(TAG, "SearchCallBack:  skList size:" + skList.size());
					mHotWords.addAll(skList);
					mSearchAdapter.notifyDataSetChanged();
				}
			} else {
				FoneUtil.showToast(mContext, "数据获取失败");
			}
		}

		@Override
		public void onFailure(Error error) {
			loading_view.setVisibility(View.GONE);
			L.i(TAG, "SearchCallBack:  " + "error.status:" + error.getStatus());
			L.i(TAG, "SearchCallBack:  " + "error.reason:" + error.getReason());
			if(error.isNetworkError()){
				FoneUtil.showToast(mContext, "网络超时,请稍后重试");
				return;
			}
			FoneUtil.showToast(mContext, "数据获取失败");
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& popWindow.searchPopWindowisShowing()) {
			popWindow.dismissSearchPopWindow();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	}
}
